#include "timers.h"


//----------------------------------------------
CTimer::CTimer(float fDelay, bool bLoop) : m_bLoop(bLoop), m_bStarted(false), m_fDelay(fDelay)
{
	STimerManager::instance()->addTimer(*this);
}

//----------------------------------------------
CTimer::~CTimer()
{
	if (m_iId != -1)
	{
		STimerManager::instance()->removeTimer(*this);
	}
}

//----------------------------------------------
void CTimer::start()
{
	m_iId = SetTimer(NULL, 0, static_cast<UINT>(m_fDelay * 1000.f), STimerManager::timerCallback);
	m_bStarted = true;
}

//----------------------------------------------
void CTimer::stop()
{
	KillTimer(NULL, m_iId);
	m_iId = -1;
	m_bStarted = false;
}

//----------------------------------------------
void CTimer::postOnTimer()
{
	if (m_bStarted && m_bLoop)
	{
		m_iId = SetTimer(NULL, m_iId, static_cast<UINT>(m_fDelay * 1000.f), STimerManager::timerCallback);
	}
}

//----------------------------------------------
DEFINE_SINGLETON(STimerManager);

//----------------------------------------------
void STimerManager::addTimer	(CTimer& oTimer)
{
	m_timers.add(&oTimer);
}

//----------------------------------------------
void STimerManager::removeTimer	(CTimer& oTimer)
{
	m_timers.remove( &oTimer );
}

//----------------------------------------------
CTimer* STimerManager::getTimer (unsigned int uiId) const
{
	for (size_t i=0; i<m_timers.size(); i++)
	{
		assert( m_timers[i] != NULL );
		if (m_timers[i]->getId() == static_cast<int>(uiId))
			return m_timers[i];
	}
	return NULL;
}

//----------------------------------------------
VOID CALLBACK STimerManager::timerCallback( HWND /*hWnd*/, UINT /*uiMsg*/, UINT uiTimerId, DWORD /*dwTime*/)
{
	CTimer* pTimer = STimerManager::instance()->getTimer(uiTimerId);

	if (pTimer != NULL)
	{
		pTimer->onTimer();
		pTimer->postOnTimer();
	}
}
